<template>
  <div class="container">
    <div class="app-container">
      <div class="add-role">
        <el-button type="primary" size="mini" @click="showDialog = true">添加角色</el-button>
      </div>
      <el-table :data="list">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <!-- v-if="row.isEdit" -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{row}">
            <el-switch
              v-if="row.isEdit"
              v-model="row.editRow.state"
              size="mini"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state === 1 ? '已启用': row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="editRowConfirm(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="btnPermisson(row.id)">分配权限</el-button>
              <el-button type="text" size="mini" @click="editRow(row)">编辑</el-button>
              <el-popconfirm
                title="你确认要删除该角色么?"
                @onConfirm="confirm(row.id)"
              >
                <el-button slot="reference" style="margin-left: 10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" style="height: 60px" align="center">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="params.pagesize"
          :current-page="params.page"
          @current-change="handleChange"
        />
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog">
      <!-- 表单内容 -->
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 权限列表 - 分配 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showPermissionDialog"
    >
      <el-tree
        ref="permTree"
        node-key="id"
        show-checkbox
        :props="defaultProps"
        :data="permissionList"
        default-expand-all
        :default-checked-keys="permIds"
        check-strictly
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { addRole, getRoleList, updateRole, delRole, getRoleDetail, assignPerm } from '@/api/role'
import { transListToTreeData } from '@/utils'
import { getPermissionList } from '@/api/permission'
export default {
  name: 'Role',
  data() {
    return {
      currentRoleId: null,
      permIds: [],
      showPermissionDialog: false, // 分配权限的弹层
      permissionList: [], // 权限列表
      defaultProps: {
        label: 'name'
      },
      showDialog: false,
      params: {
        page: 1, // 当前页码数
        pagesize: 5 // 每页的条数
      },
      list: [],
      total: 0,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async btnPermissionOK() {
      await assignPerm({ id: this.currentRoleId, permIds: this.$refs.permTree.getCheckedKeys() })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    async btnPermisson(id) {
      // 记录角色id
      this.currentRoleId = id
      // 根据id查询详情 - 权限的列表数据
      const { permIds } = await getRoleDetail(this.currentRoleId)
      // 赋值 - 树形的选中
      this.permIds = permIds
      // 1. 展示权限数据
      this.permissionList = transListToTreeData(await getPermissionList(), 0)
      // 2. 展示弹出层
      this.showPermissionDialog = true
    },
    async getRoleList() {
      const { rows, total } = await getRoleList(this.params)
      this.list = rows
      this.total = total
      this.list.forEach(item => {
        // 添加标记状态
        // 响应式: 数据变化, 视图会随之更新, 反之... 一样的道理
        // 动态添加的属性 默认不是响应式的 -> Object.defineProperty() 问题
        // vue提供了$set方法 可以保证一点 - 添加的属性具备响应式
        // this.$set('对象', '动态添加属性', '属性值')
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          description: item.description,
          state: item.state
        })
      })
    },
    // 编辑行标记状态
    editRow(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 更新数据
    async editRowConfirm(row) {
      // 1. 检查必填项 name / description
      if (row.editRow.name && row.editRow.description) {
        // 发送请求 - 更新数据
        await updateRole({
          ...row.editRow,
          id: row.id
        })
        this.$message.success('更新角色成功')
        // eslint 误判
        // row.name = row.editRow.name
        // Object.assign(target, source)
        // Object.assign(目标对象, 源对象1, 源对象2)
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      } else {
        this.$message.error('角色和描述不能为空')
      }
    },
    handleChange(value) {
      this.params.page = value
      this.getRoleList()
    },
    btnOK() {
      this.$refs.roleForm.validate(async isOK => {
        if (isOK) {
          await addRole(this.roleForm)
          this.$message.success('新增角色成功')
          this.getRoleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    // 删除角色
    async confirm(id) {
      await delRole(id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1) this.params.page--
      this.getRoleList()
    }
  }
}
</script>
<style scoped>
.add-role {
  padding: 10px;
}
</style>
